//
//  BWTabBarViewController.swift
//  新浪微博
//
//  Created by 冰凌天 on 2017/7/11.
//  Copyright © 2017年 冰凌天. All rights reserved.
//

import UIKit

/// 主控制器
class BWTabBarViewController: UITabBarController, BWTabBarDelegate {
    
    // 定时器
    fileprivate var timer : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        
        setup()
        
        setupTimer()
        
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue:BWUserShouleLoginNotification), object: nil)
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 横竖屏, 使用代码控制设备的方向, 好处: 可以再需要横屏的时候, 单独处理
    /// 设置支持的方向之后, 当前的控制器及子控制器都会遵守这个方向
    /// 如果播放视频, 通常是通过 model 展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    private func setup() {
        
        let item = UITabBarItem.appearance()
        let normal = [NSForegroundColorAttributeName : UIColor.color(red: 145, green: 145, blue: 145)]
        item.setTitleTextAttributes(normal, for: .normal)
        let selected = [NSForegroundColorAttributeName : UIColor.color(red: 253, green: 130, blue: 36)]
        item.setTitleTextAttributes(selected, for: .selected)
        
        let tabBar = BWTabBar()
        tabBar.tabBarDelegate = self as BWTabBarDelegate
        setValue(tabBar, forKeyPath: "tabBar")
    }
    
    // MARK: - 监听方法
    // 用户登录
    @objc fileprivate func userLogin(notification : NSNotification) {
        print("用户登录通知 \(notification)")
        
        // 展现登录控制器 - 通常会和UINavigationController 连用, 方便返回
        let vc = UINavigationController(rootViewController: BWOAuthViewController())
        present(vc, animated: true, completion: nil)
    }
    
    func didSelectedComposeButton() {
        print("点击按钮")
    }
    
}

// extension 类似于OC中的分类, 在Swift中还可以用来切分代码块
// 可以把相近功能的函数, 放在一个 extension中
// 便于代码维护
// 注意: 和 OC 的分类一样, extension 中不能定义属性
// MARK: - 设置界面
extension BWTabBarViewController {
    
    /// 设置所有的子控制器
    fileprivate func setupChildController() {
        
        // 获取沙盒文件路径
        let dicDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (dicDir as NSString).appendingPathComponent("demo.json")
        
        // 加载打他
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            let path = Bundle.main.path(forResource: "demo.json", ofType: "")
            
            data = NSData(contentsOfFile: path!)
        }
        
        // data 一定会有一个内容
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]] else {
            return
        }
        
//        var arrayM = [UIViewController]()
        for dict in array! {
            addChildViewController(controller(dict: dict))
//            arrayM.append(controller(dict: dict))
        }
//        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 子控制器
    fileprivate func controller(dict : [String : Any]) -> UIViewController {
        
        // 取得字典内容
        
        guard let clsName = dict["clsName"] as? String,
                let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let selectedImageName = dict["selectedImageName"] as? String,
                let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? BWBaseViewController.Type,
        let visitorInfo = dict["visitorInfo"] as? [String : String] else {
            return UIViewController()
        }
        
        // 创建视图控制器
        // 将 clsName 转换成 cls
        
        let vc = cls.init()
        
        vc.title = title
        
        vc.visitorInfo = visitorInfo
        
        vc.tabBarItem = UITabBarItem(title: title, image: UIImage(named:imageName), selectedImage: UIImage(named:selectedImageName))
        
        let nav = BWNavigationController(rootViewController: vc)
        
        return nav
    }
}

// MARK: - 时钟相关方法
extension BWTabBarViewController {
    
    fileprivate func setupTimer() {
        
        // 时间间隔建议长一些
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    @objc fileprivate func updateTimer() {
        
        if !BWNetworkManager.shared.userLogin {
            return
        }
        
        // 测试未读数量
        BWNetworkManager.shared.unreadCount { (count) in
            
            // 设置 首页 tabBarItem 的 badgeNumber
            self.tabBar.items?.first?.badgeValue = count > 0 ? "\(count)" : nil
            // 设置 App 的 badgeNumber, 从 iOS8.0 之后, 要用户授权之后才能够显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// MARK: - UITabBarControllerDelegate
extension BWTabBarViewController : UITabBarControllerDelegate {
    
    /// 将要选择 tabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        if viewController == selectedViewController && selectedIndex == 0 {
            print("重复点击")
            
            let nav = childViewControllers[0] as! UINavigationController
            let homeVc = nav.childViewControllers.first as! BWHomeViewController
            
            homeVc.tableView?.setContentOffset(CGPoint(x : 0, y : -64), animated: true)
            
            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1.0, execute: { 
                homeVc.loadData()
            })
        }
        
        // 判断目标控制器 是否是 UIViewController, 不包含子类
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}



























